<template>
	<view class="page">
		<view class="nav-bar">
			<view class="icon" @click="retreat">
				<uni-icons type="left" size="24" color="#fff"></uni-icons>
			</view>
			<text class="title">我的订单</text>
		</view>
		<view class="content">
			<!-- <orderItme></orderItme>
			<orderItme></orderItme> -->
			<!-- 商品列表 -->
			<view class="goods-list ">
				<!-- <scroll-view scroll-y style="max-height: 800rpx;min-height: 400rpx;"> -->
				<view class="cart_box">
					<view class="item_list" v-for="item in orderList" style="position: relative;">
						<view class="flex_between m-b8" style="display: flex;align-items: center;">
							<view class="" style="">
								订单编号：{{item.orderCode}}
							</view>
							<view class="cart_date" style="display: flex;font-size: 32rpx;padding-top: 10rpx;" >
								<span style="padding-top: 3rpx;">{{item.date}}</span>
								<view class="f16"
									style="margin-top: -5rpx;background-color: #0EB275;color: white;padding: 5rpx 15rpx;border-radius: 60rpx 60rpx 0 60rpx;">
									{{getDayOfWeek(item.date)}}
								</view>
							</view>
						</view>
						<view class="flex_align_conter m-b8">
							<view class="tag_b m-r4 f18">
								{{item.type == 0 ? '堂食' : '外送'}}
							</view>
							<view class="cart_date f18">
								{{item.siteName}}
							</view>
						</view>
						<view class="" v-if="item.dictDataList">
							<view class=""
								v-if="item.dictDataList && item.dictDataList.breakfast && (item.dictDataList.breakfast.comboList.length > 0 || item.dictDataList.breakfast.dishList.length > 0 )">
								<orderTitle content="早餐"></orderTitle>
								<setMealOrder :availablePreview="true"
									v-for="d in item.dictDataList.breakfast.comboList" :date="item.date" :item="d">
								</setMealOrder>
								<setMealOrder :availablePreview="true" :date="item.date" v-for="d in item.dictDataList.breakfast.dishList"
									:item="d">
								</setMealOrder>
							</view>
							<view class=""
								v-if="item.dictDataList && item.dictDataList.lunch && (item.dictDataList.lunch.comboList.length > 0 || item.dictDataList.lunch.dishList.length > 0 )">
								<orderTitle content="午餐"></orderTitle>
								<setMealOrder :availablePreview="true" :date="item.date" v-for="d in item.dictDataList.lunch.comboList"
									:item="d">
								</setMealOrder>
								<setMealOrder :availablePreview="true" :date="item.date" v-for="d in item.dictDataList.lunch.dishList"
									:item="d">
								</setMealOrder>
							</view>
							<view class=""
								v-if="item.dictDataList && item.dictDataList.supper && (item.dictDataList.supper.comboList.length > 0 ||item.dictDataList.supper.dishList.length > 0 )">
								<orderTitle content="晚餐"></orderTitle>
								<setMealOrder :availablePreview="true" :date="item.date" v-for="d in item.dictDataList.supper.comboList"
									:item="d">
								</setMealOrder>
								<setMealOrder :availablePreview="true" :date="item.date" v-for="d in item.dictDataList.supper.dishList"
									:item="d">
								</setMealOrder>
							</view>
						</view>
						<view class="flex_between total_box">
							<view class="total flex_align_conter">
								<view class="f18">合计
								</view>
								<view class="price f18">¥ <span style="font-size: 50rpx;">{{item.totalAmount}}</span>
								</view>
							</view>

							<!-- {{item.status}} -->
							<!-- {{sBeforeToday(item.date)}} -->
							<!-- v-if="sBeforeToday(item.date) && item.status != 3" -->
							<view class="flex_align_conter" style="color: #0EB275;"
								v-if="sBeforeToday(item.date) && item.status != 3">
								<!-- 已完成 -->
								<image src="/static/stateIcon/3.png"
									style="width: 107px;height: 107px;position: absolute;right: 25px;top: 20px;"
									mode=""></image>
							</view>

							<view class="flex_align_conter"
								v-if="!sBeforeToday(item.date) && item.status != 2 && item.status != 3">
								<button class="btn_b cu-btn block bg-grey-plain round"
									 @click="cancelReservation(item)" style="font-size: 36rpx;">取消预订
								</button>
								<!-- :disabled="!isTodayOrNextWeek(item.date)" -->
								<!-- :disabled="!isTodayOrNextWeek(item.date)" -->
								<button style="font-size: 36rpx;"
									class="btn_b cu-btn block bg-green round m-l8" @click="modifyOrder(item)">修改订单
								</button>
							</view>
							<!-- {{!sBeforeToday(item.date)}} -->

							<!-- {{item.status}} -->
							<view class="flex_align_conter" style="color: #0EB275;"
								v-if="item.status == 2 && !sBeforeToday(item.date) && item.status != 3">
								<!-- 审核中 -->
								<image src="/static/stateIcon/2.png"
									style="width: 107px;height: 107px;position: absolute;right: 25px;top: 20px;"
									mode=""></image>

							</view>

							<view class="flex_align_conter" style="color: #0EB275;" v-if="item.status == 3">
								<image src="/static/stateIcon/1.png"
									style="width: 107px;height: 107px;position: absolute;right: 25px;top: 20px;"
									mode=""></image>
							</view>
						</view>
					</view>
				</view>
				<!-- </scroll-view> -->
			</view>
		</view>

		<navigationBar tabbarIndex="2"></navigationBar>
	</view>
</template>
<script>
	import {
		getOrderListAPI,
		delOrderAPI,
		getClockApprovalAPI,
		getCbreachdy,
		delOrderAPIapply
	} from '@/api/index.js'
	import setMealReservation from '@/components/common/setMealReservation.vue'
	import setMealOrder from '@/components/common/setMealOrder.vue'
	import orderTitle from '@/components/common/orderTitle.vue'
	import navigationBar from '@/components/common/navigationBar.vue'
	import dayjs from 'dayjs'
	import {
		getDayOfWeek,
		isInTimeRange
	} from '../../utils/utils'
	// import orderItme from '@/components/common/orderItme.vue'
	// uni.hideTabBar()
	export default {
		name: '',
		data() {
			return {
				orderList: [],
				clockApproval: {},
				countNumber: 0,
				userInfo: this.$store.state.user.userInfo,

			}
		},
		components: {
			setMealReservation,
			setMealOrder,
			orderTitle,
			navigationBar,
			// orderItme
		},
		onLoad(e) {
			this.getlist()
			this.getClockApproval()
			this.countNum()
		},
		methods: {
			async countNum() {
				const res = await getCbreachdy(this.userInfo.userId)
				console.log(res.data)
				this.countNumber = res.data
			},
			sBeforeToday(dateStr) {
				const inputDate = dayjs(dateStr).startOf('day'); // 去掉时间部分，只比较日期
				const today = dayjs().startOf('day'); // 今天的 00:00:00
				return inputDate.isBefore(today);
			},
			isTodayOrNextWeek(inputDate) {
				// 处理输入：支持Date对象或日期字符串
				let date;
				if (inputDate instanceof Date) {
					date = new Date(inputDate);
				} else if (typeof inputDate === 'string') {
					date = new Date(inputDate);
					if (isNaN(date.getTime())) {
						throw new Error('传入必须是有效的日期或日期字符串');
					}
				} else {
					throw new Error('传入必须是Date对象或有效的日期字符串');
				}

				// 标准化日期（仅保留年月日，清除时间部分）
				const normalize = (d) => {
					const newDate = new Date(d);
					newDate.setHours(0, 0, 0, 0);
					return newDate;
				};

				const today = normalize(new Date());
				const checkDate = normalize(date);

				// 当天之前的日期：不允许
				if (checkDate < today) {
					return false;
				}

				// 当天日期：允许
				if (checkDate.getTime() === today.getTime()) {
					return true;
				}

				// 计算本周日的日期（JavaScript中周日为0，周六为6）
				const todayDay = today.getDay() || 7; // 转换为：周一=1，周二=2...周日=7
				const daysToSunday = 7 - todayDay;
				const thisSunday = normalize(new Date(today));
				thisSunday.setDate(today.getDate() + daysToSunday);

				// 当周内今天之后的日期：不允许
				if (checkDate <= thisSunday) {
					return false;
				}

				// 计算下周日的日期（本周日加7天）
				const nextSunday = normalize(new Date(thisSunday));
				nextSunday.setDate(thisSunday.getDate() + 7);

				// 下周一到下周日：允许；超过下周日：不允许
				return checkDate <= nextSunday;
			},
			getDayOfWeek(dateStr) {
				console.log(dateStr)
				const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const date = new Date(dateStr);
				console.log(date)
				const dayIndex = date.getDay(); // 0 是星期日，1 是星期一，...，6 是星期六
				return days[dayIndex];
			},
			cancelReservation(item) {

				const obj = this.checkDateAndTimeWithDayjs(item.date)

				// if (obj.isToday && obj.isAfter9AM) {
				// 	if (this.clockApproval.configValue == 0) return this.$modal.msg('已超过修改限次')
				// }
				// if (obj.isToday && !obj.isAfter9AM) {
				// 	if (this.clockApproval.configValue == 0 && this.countNumber >= 3) return this.$modal.msg('已超过修改限次')
				// }
				
				// if(!obj.isToday){
				// 	if (!isInTimeRange()) {
				// 		// 12
				// 		this.$modal.msg("抱歉，当前订餐时间未开放")
				// 		return
				// 	}
				// }
				
				if(this.isTimeOverThisWeek(item.date)){
					if(!obj.isToday){
						if (!isInTimeRange()) {
							// 12
							this.$modal.msg("抱歉，当前订餐时间未开放")
							return
						}
					}
				}
				
				
				
				if(obj.isToday && obj.isAfter9AM){
					return this.$modal.msg('已超过修改时间')
				}else if(obj.isToday && !obj.isAfter9AM){
					if (this.$store.state.user.userInfo.alterNum >= 3 && this.clockApproval.configValue == 0) {
						 return this.$modal.msg('已超过修改次数')
					}
				}
				// console.log(item);
				// return
				this.$modal.confirm(`确定取消 ${item.date} 的预约吗？`).then(async () => {
					// console.log('删除');
					
					if(obj.isToday){
						if (this.$store.state.user.userInfo.alterNum >= 3 && this.clockApproval.configValue == 0) {
							 return this.$modal.msg('已超过修改次数')
						}else if (this.$store.state.user.userInfo.alterNum >= 3 && this.clockApproval.configValue == 1) {
							 // return this.$modal.msg('已超过修改次数')
							 const res = await delOrderAPIapply({
							 	orderId: item.orderId,
								orderCode:item.orderCode,
							 	uuid: item.uuid
							 })
							 this.$modal.msg(res.msg)
						}else{
							const res = await delOrderAPI({
								orderId: item.orderId,
								uuid: item.uuid
							})
							this.$modal.msg(res.msg)
						}
						
						// const res = await delOrderAPIapply({
						// 	orderId: item.orderId,
						// 	uuid: item.uuid
						// })
						
					}else{
						const res = await delOrderAPI({
							orderId: item.orderId,
							uuid: item.uuid
						})
						this.$modal.msg(res.msg)
					}
					
					
					setTimeout(() => {
						this.getlist()
					}, 1000)
				})
			},
			checkDateAndTimeWithDayjs(targetDateStr) {
				const targetDay = dayjs(targetDateStr);
				if (!targetDay.isValid()) {
					return {
						isToday: false,
						isAfter9AM: false,
						error: '无效的日期格式'
					};
				}
				const now = dayjs();
				const isToday = targetDay.isSame(now, 'day');

				let isAfter9AM = false;
				if (isToday) {
					const currentHour = now.hour();
					console.log(currentHour)
					isAfter9AM = currentHour > 8;
				}
				return {
					isToday,
					isAfter9AM
				};
			},
			async getClockApproval() {
				const res = await getClockApprovalAPI('nine.clock.approval')
				this.clockApproval = res.data
			},
			isTimeOverThisWeek(targetDateStr) {
			  // 将目标日期字符串转换为Date对象
			  const targetDate = new Date(targetDateStr);
			  targetDate.setHours(0, 0, 0, 0); // 标准化目标日期的时间部分
			  
			  // 获取当前时间
			  const now = new Date();
			  
			  // 获取本周的第一天（周一）
			  const startOfWeek = new Date(now);
			  startOfWeek.setHours(0, 0, 0, 0);
			  
			  // 计算本周一：当前日期减去当前星期几（0-6，周日为0）再加上1（如果是周日需要特殊处理）
			  const dayOfWeek = now.getDay(); // 0是周日，1是周一，...，6是周六
			  const diffToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
			  startOfWeek.setDate(now.getDate() + diffToMonday);
			  
			  // 获取本周的最后一天（周日）
			  const endOfWeek = new Date(startOfWeek);
			  endOfWeek.setDate(startOfWeek.getDate() + 6);
			  endOfWeek.setHours(23, 59, 59, 999); // 设置为周日的最后一刻
			  
			  // 判断目标日期是否在本周范围内
			  return targetDate < startOfWeek || targetDate > endOfWeek;
			},
			modifyOrder(item) {

				const obj = this.checkDateAndTimeWithDayjs(item.date)

				// if (item.num >= 3) {
				// 	return this.$modal.msg('已超过修改限次')
				// }
				// if (obj.isToday && obj.isAfter9AM) {
				// 	if (this.clockApproval.configValue == 0) return this.$modal.msg('已超过修改限次')
				// }
				// if (obj.isToday && !obj.isAfter9AM) {
				// 	if (this.clockApproval.configValue == 0 && this.countNumber >= 3) return this.$modal.msg('已超过修改限次')
				// }
				
				// if(obj.isToday && obj.isAfter9AM){
				// 	return this.$modal.msg('已超过修改时间')
				// }else if(obj.isToday && !obj.isAfter9AM){
				// 	if (this.$store.state.user.userInfo.alterNum >= 3 && this.clockApproval.configValue == 0) {
				// 		 return this.$modal.msg('已超过修改次数')
				// 	}
				// }
				console.log(this.isTimeOverThisWeek(item.date))
				if(this.isTimeOverThisWeek(item.date)){
					if(!obj.isToday){
						if (!isInTimeRange()) {
							// 12
							this.$modal.msg("抱歉，当前订餐时间未开放")
							return
						}
					}
				}
				
				
				
				console.log(obj.isAfter9AM)
				if(obj.isToday && obj.isAfter9AM){
									return this.$modal.msg('已超过修改时间')
								}else if(obj.isToday && !obj.isAfter9AM){
									if (this.$store.state.user.userInfo.alterNum >= 3 && this.clockApproval.configValue == 0) {
										 return this.$modal.msg('已超过修改次数')
									}
								}

				// console.log(orderId);
				this.$tab.navigateTo(`/subpackages/user/pages/order/amendOrder?orderId=${item.orderId}&date=${item.date}&num=${item.num}&siteName=${item.siteName}&siteId=${item.siteId}`)
			},
			async getlist() {
				uni.showLoading({
					title: '加载中...',
				})
				// const res = await getComboDetailAPI(this.comboId)

				const res = await getOrderListAPI()
				uni.hideLoading()
				this.orderList = res.rows
				this.orderList.forEach(el => {
					// 获取当前时间戳（13位）
					const timestamp = Date.now();
					// 生成10位随机数字
					const random = Math.floor(Math.random() * 9000000000) + 1000000000;
					// 拼接成唯一ID（23位：13位时间戳 + 10位随机数）
					el.uuid = `${timestamp}${random}`;
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.page {
		position: relative;
		min-height: 100vh;
		background: #F2F2F2;
		// padding-bottom: 30rpx;

		.nav-bar {
			position: relative;
			display: flex;
			align-items: center;
			height: 105px;
			justify-content: center;
			color: #323232;
			font-size: 36rpx;
			// margin-bottom: 40rpx;
			background: #FFFFFF;
			// padding-top: 40rpx;

			.icon {
				position: absolute;
				left: 20rpx;
				top: 0;
				transform: translateY(50%);
			}

			.back-icon {
				position: absolute;
				left: 30rpx;
			}
		}

		.goods-list {
			margin-bottom: 20rpx;

			.item_list {

				background-color: #FFFFFF;
				padding: 20rpx 32rpx;
				border-radius: 16rpx;
				margin-bottom: 20rpx;

				.total_box {
					margin-top: 10rpx;
				}
			}

			.tag_b {
				padding: 2rpx 6rpx;
				font-size: 20rpx;
				color: #0EB275;
				border: 2rpx solid #6ED1AC;
				border-radius: 8rpx;
			}

			.btn_b {
				height: 56rpx;
			}

			.total {
				// margin-top: 40rpx;
				font-size: 24rpx;

				.price {
					color: #0EB275;
					margin-left: 8rpx;
				}
			}
		}

		.content {
			padding: 20rpx 20rpx 180rpx;
		}
	}
</style>